#include "hubapplnk.h"

#include <QDesktopServices>
#include <QFileIconProvider>
#include <QFileInfo>
#include <QMessageBox>
#include <QPainter>
#include <QUrl>

#define HUB_LINKS_DIR QString("./hub_links/")

HubAppLNK::HubAppLNK(const QString &lnk_name, int new_wd, QWidget *parent)
    : QPushButton(parent), wd(new_wd)
{
    qDebug() << "HubAppLNK 创建了";

    resize(wd, wd);
    setFlat(true);
    setCursor(Qt::PointingHandCursor);

    // 根据快捷方式获取绝对路径
    QString temp_path = HUB_LINKS_DIR + lnk_name;
    if (! temp_path.endsWith(".lnk"))
        temp_path.append(".lnk");
    QFileInfo lnk_file_info = QFileInfo(temp_path);
    absolute_path = lnk_file_info.canonicalFilePath();

    connect(this, &QPushButton::clicked, [this]()
    {
        bool ret = QDesktopServices::openUrl(QUrl::fromLocalFile(absolute_path));

        if (!ret)
            QMessageBox::critical(this, "打开错误", "我们遇到了一些意想不到的错误，\n打开 " + absolute_path + " 失败");

        emit have_clicked();
    });
}

void HubAppLNK::paintEvent(QPaintEvent * event)
{
    QPainter painter(this);
    QFileInfo file_info = QFileInfo(absolute_path);
    QPixmap icon_pixmap = QFileIconProvider().icon(file_info).pixmap(QSize(wd, wd));
    painter.drawPixmap(0, 0, wd, wd, icon_pixmap);
}

HubAppLNK::~HubAppLNK()
{
    qDebug() << "HubAppLNK 销毁了";
}
